$(function(){
	$("#functionNav").attr("href",navAddr);
	String.prototype.trim=function(){
	   return this.replace(/(^\s*)|(\s*$)/g, "");
	}
	$('.dateInput').datetimepicker({
		format: 'yyyy-mm-dd',
        forceParse: 0,
        todayBtn:  1,
        autoclose: 1,
        todayHighlight: 1,
        minView: 2,
        bootcssVer:3
});
	//表格表头列
	var searchParams = $("#stat-form").serializeObject();
	var tableColumn = createColumn(searchParams);
	
	//初始化下拉列表
	initSelect(searchParams.sqbmid);
	//必须在initSelect()之后调用
	initTableHead();
	initTableFoot();
	createTable();
	
	//统计按钮
	$('#stat-czy-query').click(function(){
		searchParams = $("#stat-form").serializeObject();
		tableColumn = createColumn(searchParams);
		if(!isValidStr(searchParams.y)){
			alertFunc("总坐标不能为空！");
			return;
		}
		var y = $("#y").val();
		if(y=="xf_month"){
			if(!isValidStr(searchParams.year)){
				alertFunc("统计年度不能为空！");
				return;
			}
		}
		initTableHead();
		initTableFoot();
		createTable();
	});
	$("#y").change(function(){
		var y = $("#y").val();
		if(y=="xf_month"){
			$("#tjnd_div").show();
			$("#cpfl_div").show();
			$("#cpjb_div").show();
			$("#bgbm_div").show();
			$("#xfsj_div").hide();
		}else if(y=="cpjb"){
			$("#tjnd_div").hide();
			$("#xfsj_div").show();
			$("#cpfl_div").show();
			$("#cpjb_div").hide();
			$("#bgbm_div").show();
		}else if(y=="cpfl"){
			$("#tjnd_div").hide();
			$("#xfsj_div").show();
			$("#cpfl_div").hide();
			$("#cpjb_div").show();
			$("#bgbm_div").show();
		}else if(y=="bgbm"){
			$("#tjnd_div").hide();
			$("#xfsj_div").show();
			$("#cpfl_div").show();
			$("#cpjb_div").show();
			$("#bgbm_div").hide();
		}
		$("#sd1").val("");
		$("#bgbm").val("");
		$("#cpfl1").val("");
		$("#cpjb").val("");
		$("#tjnd").val("");
		$("#xfsj_start").val("");
		$("#xfsj_end").val("");
	});
	$('#stat-czy-export').click(function(){
//		if(!isValidStr(searchParams.czrid)){
//			alertFunc("请先统计再进行导出（操作人不能为空）！");
//			return;
//		}
//		
		searchParams.title = $('#table-head').html();
		searchParams.author = userInfo.username;
		searchParams.type = 'xfgl';
		
		$.fileDownload(ProjectName+'/utilizeState.export.do', {
			data: $.param(searchParams),
			httpMethod: "post",
			successCallback: function (url) {
				console.log('文件下载成功！')
			},
			failCallback: function (responseHtml, url, error) { 
				console.log('文件下载失败！')
			}
		});
	});
	
	function createTable(){
		//导出按钮设为不可用
		$('#stat-czy-export').attr('disabled', true);
		$('#stat-show').bootstrapTable('destroy');		
		$('#stat-show').bootstrapTable({
			url: ProjectName+'/utilizeState.stateXfgl.do',
			method: 'get',
			sidePagination: "server",
			queryParams: searchParams,
			columns: tableColumn,
			onLoadSuccess: function(d){  
				//加载成功时执行  
				data=d;
				//导出按钮可用
				$('#stat-czy-export').attr('disabled', false);
	        }
		});
	};
	
	
	function isValidStr(str){
		if(str && str.trim().length>0)
			return true;
		return false;
	}
	
	function initSelect(){
		//统计年度下拉列表初始化
		var year = new Date().getFullYear();
		var arr = [];
		for(var i=2016; i<=year; i++){
			var map = {};
			map['key'] = i;
			map['value'] = i;
			arr.push(map);
		}
		loadSelect("#tjnd", arr,'value','key');
		$("#tjnd option[value="+year+"]").attr("selected", true);
		
		cpfl1Json = ajaxResult("get",false,ProjectName+"/sysmanage.getIdNameByParentid.do", {"tableName":'jb_cplb', 'parentid':'0'});
		cpfl1Json = cpfl1Json.rows;
		loadSelect("#cpfl1",cpfl1Json,'id','name');
		cpjbJson = ajaxResult("get",false,ProjectName+"/sysmanage.getIdAndNameInJb.do", {"tableName":'jb_cpjb'});
		cpjbJson = cpjbJson.rows;
		loadSelect("#cpjb",cpjbJson,'id','name');
		sd1Json = ajaxResult("get",false,ProjectName+"/sysmanage.getIdNameByParentid.do", {"tableName":'jb_nd', 'parentid':'0'});
		sd1Json = sd1Json.rows;
		loadSelect("#sd1",sd1Json,'id','name');
		bgbmJson = ajaxResult("get",false,ProjectName+"/sysmanage.getIdAndNameInJb.do", {"tableName":'jb_bgbm'});
		bgbmJson = bgbmJson.rows;
		loadSelect("#bgbm",bgbmJson,'id','name');
	}
	
	function initTableHead(){
		var html = '藏品修复统计';
		var con = '';
		var year = new Date().getFullYear();
		for(var key in searchParams){
			var value = searchParams[key];
			if(!isValidStr(value+""))
				continue;
			if(key == 'sd1')
				con += '藏品时代：'+sd1Json[index(sd1Json, value)].name+'；';
			if(key == 'cpfl1')
				con += '藏品分类：'+cpfl1Json[index(cpfl1Json, value)].name+'；';
			if(key == 'cpjb')
				con += '藏品级别：'+cpjbJson[index(cpjbJson, value)].name+'；';
			if(key == 'bgbm')
				con += '保管部门：'+bgbmJson[index(bgbmJson, value)].name+'；';
			if(key == 'year')
				con += '统计年度：'+value+'；';
			if(key == 'xfsj_start')
				con += '统计时间：'+value+'';
			if(key == 'xfsj_end')
				con += '-'+value+'；';
		}
		
		if(con)
			html += ' ( ' + con + ' )';
		$('#table-head').html(html);
	}
	
	function initTableFoot(){
		if(!userInfo)
			getUserRight();
		
		var content = "";
		content += '制表人：'+userInfo.username+'<br>';
		content += '统计时间：'+nowDate();
		
		$('#table-foot').html(content);
	}

	//生成table第一行的列头
	function createColumn(paras){
		var enToCn = {'xflx':'修复类型'};
		var cols, tableName;
		var  y_ = paras.y;
		//否则，请求后台，获取列
		cols = ajaxResult("get",false,ProjectName+"/colstat.getCollectionTotalCols.do", {"tableName":"jb_xflx", "type":paras.x});
		cols = cols.data;
		
		//生成列，即表格第一行的列名
		var tColumn = [];
		var firstCol = {};
		firstCol['field'] = y_;
		firstCol['align'] = 'center';
		firstCol['title'] = enToCn[y_];
		tColumn.push(firstCol);
		for(var key in cols){
			map = {}
			map['field'] = key;
			map['title'] = cols[key];
			map['align'] = 'center';
			tColumn.push(map);
		}

		var footCol = {};
		footCol['field'] = "hjnum";
		footCol['align'] = 'center';
		footCol['title'] = "合计";
		tColumn.push(footCol);
		return tColumn;
	}

	//获取指定id值的下标索引
	//arr的格式：[{id:diancangbu, name:'典藏部'}, ...]
	function index(arr, key){
		var i = -1;
		$.each(arr, function(index, item){
			if(item.id==key){
				i = index;
				return false;
			}
		});
		return i;
	}
});